<template>
  <div class="flex-column h-100">
    <div class="flex justify-between">
      <div class="flex mb-10">
        <el-button v-if="permission.export" type="primary" size="mini" @click="exportClick">{{
          $t('EXPORT')
        }}</el-button>
      </div>
      <div class="flex justify-end flex-wrap">
        <el-date-picker
          v-model="dateTime"
          type="datetimerange"
          align="right"
          size="mini"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          unlink-panels
          class="mb-10"
          range-separator="-"
          :start-placeholder="$t('START_DATE')"
          :end-placeholder="$t('END_DATE')"
          :picker-options="pickerOptions"
          style="width: 320px"
        />
        <el-select
          v-model="operateItem"
          clearable
          filterable
          :placeholder="$t('SELECT_NAME', { msg: $t('OPERATE_ITEM') })"
          size="mini"
          class="ml-10 mb-10"
          style="width: 200px"
        >
          <el-option
            v-for="(item, index) in operateList"
            :key="index"
            :label="$t(item.label)"
            :value="item.value"
          />
        </el-select>
        <el-input
          v-model="keyword"
          clearable
          :placeholder="$t('ENTER_NAME', { msg: $t('REAL_NAME') })"
          size="mini"
          class="ml-10 mb-10"
          style="width: 200px"
        />
        <el-button type="primary" class="ml-10 mb-10" size="mini" @click="$debounce(query)">{{
          $t('QUERY')
        }}</el-button>
      </div>
    </div>
    <CommonTable
      ref="table"
      :table-data="tableData"
      :current-page.sync="currentPage"
      :page-size.sync="pageSize"
      :total="total"
      @loadData="loadData"
    />
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import { pickerOptionsClassOneWeek } from '@/utils/common.js'
  import { exportExcel } from '@/utils/jsonToExcel.js'
  import OperateLogApi from '@/api/system/OperateLogApi.js'
  import FuncApi from '@/api/system/FuncApi'
  import AuthApi from '@/api/system/AuthApi'
  import ParamApi from '@/api/system/ParamApi'
  import CommonTable from './components/CommonTable.vue'
  let searchData = {} // 查询参数 只有点了查询有效
  const filterTree = (list, arr) => {
    list.forEach(ele => {
      if (ele.funcType === 'MENU' && ele.enName) {
        arr.push(ele)
      } else {
        if (ele.children && ele.children.length) {
          filterTree(ele.children, arr)
        }
      }
    })
    return arr
  }
  export default {
    components: { CommonTable },
    data() {
      return {
        operateList: [],
        operateItem: '', // 操作项
        dateTime: [],
        keyword: '',
        pickerOptions: pickerOptionsClassOneWeek(this),
        tableData: [],
        currentPage: 1,
        pageSize: 20,
        total: 0
      }
    },
    computed: {
      ...mapGetters(['dictList', 'getUser', 'getRoles', 'getUserId']),
      permission() {
        return this.$store.getters.getAuthData('sys:operateLog')
      }
    },
    created() {
      this.getFunc()
    },
    activated() {
      this.loadData()
    },
    methods: {
      query() {
        this.currentPage = 1
        searchData = {
          startTime: '',
          endTime: '',
          item: '',
          keyword: ''
        }
        if (this.dateTime) {
          searchData.startTime = this.dateTime[0]
          searchData.endTime = this.dateTime[1]
        }
        if (this.operateItem) searchData.item = this.operateItem
        if (this.keyword) searchData.keyword = this.keyword
        this.loadData()
      },
      // 获取操作项
      async getFunc() {
        const list = await FuncApi.tree()
        if (!list) return
        const funcList = filterTree(list, [])
        let filterFuncList = funcList
        // 根据当前登录用户的角色，获取角色对应的功能列表
        const { targetList } = await AuthApi.getAuth(this.getRoles[0], 'ROLE_FUNC')
        if (!targetList) return
        if (targetList.length) {
          filterFuncList = funcList.filter(i => targetList.includes(i.funcId))
        }
        const enNameList1 = filterFuncList
          .filter(i => {
            if (i.sysId === 'AFS_OEN') {
              return i
            }
          })
          .map(i => i.enName)
        const enNameList2 = filterFuncList
          .filter(i => {
            if (i.sysId === 'AFS_IOT') {
              return i
            }
          })
          .map(i => i.enName)
        this.operateList = Array.from(new Set(enNameList1.concat(enNameList2))).map(i => {
          return {
            label: i,
            value: i
          }
        })
        const { list: disabledList = [] } = await ParamApi.page({
          page: 1,
          size: 10000,
          keyword: 'OPERATE_ITEM_DISABLED'
        })
        if (disabledList && disabledList.length) {
          this.operateList = this.operateList.filter(i => {
            return !JSON.parse(disabledList[0].paramValue).includes(i.value)
          })
        }
        // 首页分为系统首页-拓扑图和系统首页-GIS展示
        const homeIndex = this.operateList.findIndex(i => i.value === 'HOME')
        if (homeIndex !== -1) {
          this.operateList.splice(
            homeIndex + 1,
            0,
            { label: 'HOME_GIS_MAP', value: 'HOME_GIS_MAP' },
            { label: 'HOME_TOPOLOGY_MAP', value: 'HOME_TOPOLOGY_MAP' }
          )
        }
        this.operateList.unshift(
          {
            label: 'LOGIN',
            value: 'LOGIN'
          },
          {
            label: 'MOD_PWD',
            value: 'MOD_PWD'
          },
          {
            label: 'APPROVAL_STATUS_AUTH',
            value: 'APPROVAL_STATUS_AUTH'
          },
          {
            label: 'LOG_OUT',
            value: 'LOG_OUT'
          }
        )
      },
      loadData() {
        const data = {
          page: this.currentPage,
          size: this.pageSize,
          ...searchData
        }
        OperateLogApi.page(data).then(res => {
          res = res || {}
          const list = res.list || []
          this.tableData = list
          this.total = res.total || 0
        })
      },
      exportClick() {
        const data = {
          page: 1,
          size: 10000,
          currentUserId: this.getUser.userId // 记录操作日志用，不要删除此传参！
        }
        if (this.keyword) data.keyword = this.keyword
        if (this.operateItem) data.item = this.operateItem
        if (this.dateTime) {
          data.startTime = this.dateTime[0]
          data.endTime = this.dateTime[1]
        }
        this.$confirm(
          this.dateTime && this.dateTime.length > 0
            ? this.$t('LOG_IMPORT_TIME_TIP')
            : this.$t('LOG_IMPORT_TIP') + '<br>' + this.$t('EXPORT_ALL_TIPS', { count: 10000 }),
          { type: 'warning', dangerouslyUseHTMLString: true }
        )
          .then(() => {
            OperateLogApi.page(data).then(res => {
              console.log(res)
              const { list = [] } = res
              this.exportExcel(list)
            })
          })
          .catch(() => {})
        // OperateLogApi.expData(data).then(res => {
        //   downloadFile(res, `${this.$t('LOG_TYPE_OPREATION')}.xlsx`)
        // }).catch(() => {})
      },
      exportExcel(data) {
        const hearder = [
          this.$t('OPERATE_TIME'),
          this.$t('REAL_NAME'),
          this.$t('USER_ID'),
          this.$t('OPERATE_ITEM'),
          this.$t('OPERATE_COMMAND'),
          this.$t('OPERATE_OBJECT'),
          this.$t('OPERATE_CONTENT'),
          // this.$t('OPERATE_RESULT'),
          this.$t('OPERATOR_ID')
        ]
        const jsonExcel = []
        const sheetNames = [this.$t('LOG_TYPE_OPREATION')]
        const relates = data.map((i, index) => {
          let content = null
          if (i.content && i.content.length > 5) {
            try {
              content = JSON.parse(i.content || '{}')
            } catch (e) {
              console.log(e)
            }
          }
          const item = [
            i.recordTime,
            i.realName,
            i.userId,
            this.$t(i.item),
            this.$t(i.terminal),
            i.object,
            content && content.i18nKey
              ? this.$t(content.i18nKey, content).replace(i.userId, (i.realName || i.userId)).replace('<br/>', ' ')
              : '',
            // i.operateResult
            //   ? this.$t('SUCCESS')
            //   : this.$t('OPERATE_RESULT_FAILURE'),
            i.ip
          ]
          return item
        })
        jsonExcel.push([hearder, ...relates])
        exportExcel(jsonExcel, this.$t('LOG_TYPE_OPREATION'), sheetNames, 'array')
        this.addLog()
      },
      addLog() {
        const obj = {
          api: '/',
          item: 'LOG_TYPE_OPREATION',
          object: '/',
          terminal: 'EXPORT',
          operateResult: true,
          realName: this.getUser.realName,
          content: JSON.stringify({
            currentUserId: this.getUserId,
            i18nKey: 'EXPORT_LOG_TYPE_OPREATION_LOG'
          })
        }
        OperateLogApi.addLog(obj)
      }
    }
  }
</script>
<style lang="scss" scoped></style>
